package com.beiding.dao.impl;

import com.beiding.timeout.bean.DelayTaskPersistence;
import com.beiding.timeout.dao.TasksMap;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

@Repository
public class TasksMapImpl implements TasksMap<String> {

    private HashOperations<String, String, DelayTaskPersistence<String>> operations;

    public TasksMapImpl(RedisConnectionFactory factory, JdkSerializationRedisSerializer jdkSerializationRedisSerializer, StringRedisSerializer stringRedisSerializer) {

        //定值redisTemplate
        RedisTemplate<String, DelayTaskPersistence<String>> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        //设置序列化器
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jdkSerializationRedisSerializer);

        redisTemplate.afterPropertiesSet();

        operations = redisTemplate.opsForHash();

    }

    @Override
    public DelayTaskPersistence<String> get(String id) {
        return operations.get("test:tasks", id);
    }

    @Override
    public void remove(String id) {
            operations.delete("test:tasks", id);
    }

    @Override
    public String save(DelayTaskPersistence<String> persistence) {
        String id = toId(persistence.getPayload(), persistence.getType());
        persistence.setId(id);
        operations.put("test:tasks", id, persistence);
        return id;
    }

    @Override
    public void removeByPayloadAndType(String payload, String type) {
        remove(toId(payload, type));
    }

    private String toId(String payload, String type) {
        return payload.hashCode() + "-" + type;
    }


}
